package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mappers.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.vo.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public ResultInfo deleteByid(Long id) {
       Integer dishCounts= categoryMapper.countDishByCategoryId(id);
       if(dishCounts>0)
       {
           throw new CustomException("该分类还有菜品关联，不能删除");
//           return ResultInfo.error("你的地嘘里面还有菜跟这个分类关联，请先删除地嘘里面的菜!");
       }
       Integer setmealCounts= categoryMapper.countSetmealByCategoryId(id);
        if(setmealCounts>0)
        {  throw new CustomException("该分类还有套餐关联,不能不删除");
//            return ResultInfo.error("你的赛特米尔里面还有菜跟这个分类关联，请先删除赛特米尔里面的菜!");
        }
        categoryMapper.deleteById(id);
        return ResultInfo.success(null);
    }

    @Override
    public void update(Category category) {
        category.setUpdateTime(new Date());
        category.setUpdateUser(1L);
        categoryMapper.update(category);
    }

    @Override
    public void save(Category category) {
        //调用工具类用雪花算法生成ID
        category.setId(IdUtil.getSnowflake(1,1).nextId());
        //初始化创建更新时间和操作者
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        category.setCreateUser(1L);
        category.setUpdateUser(1L);
        //将数据插入表
        categoryMapper.save(category);
    }

    @Override
    public List<Category> findPage(Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Category> all = categoryMapper.findAll();
        return all;
    }

    @Override
    public List<Category> findAll() {
       return categoryMapper.findAll();
    }
}
